﻿/*
 * Copyright(C) 2012,ajayumi 保留所有权利。( All rights reserved. )
 * 
 * 文件名称：ListUserControlBase.cs
 * 摘    要：
 * 当前版本：1.0
 * 作    者：黄乙冬 (ajayumi)
 * 创建日期：2012年5月24日
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using ajayumi.Platform.Web.Localization;
using System.Collections;

namespace ajayumi.Platform.Web
{
    public class ListUserControlBase : UserControlBase, IPagination
    {
        public const int SUB_SIZE = 10;   //数字分页显示最大个数

        /// <summary>
        /// 数据源控件，DataKey信息
        /// </summary>
        protected string DataKeyName
        {
            get;
            set;
        }

        #region BasePage Members

        /// <summary>
        /// 重写该方法，实现自定义分页
        /// </summary>
        public override void InitInvoke()
        {
            ShowListPage();

            if (!IsPostBack)
            { BindData(); }

            RegDigitPageHandler();
            RegPaginationHandler();
        }

        #endregion

        #region IPagination

        public bool IsPaginationable
        {
            get;
            set;
        }

        public virtual string FirstPageConID
        {
            get { return "lbtnFirst"; }
        }

        public virtual string PrevPageConID
        {
            get { return "lbtnPrev"; }
        }

        public virtual string NextPageConID
        {
            get { return "lbtnNext"; }
        }

        public virtual string LastPageConID
        {
            get { return "lbtnLast"; }
        }

        public string DigitPageConID
        {
            get { return "lbDigitPage"; }
        }

        public string PageDetailConId
        {
            get { return "lbPageDetail"; }
        }

        public void FirstPage()
        {
            this.PageIndex = 1;
            BindData();
        }

        public void PrevPage()
        {
            if (this.PageIndex != 1)
            {
                this.PageIndex = Convert.ToInt32(this.PageIndex) - 1;
            }
            BindData();
        }

        public void NextPage()
        {
            if (this.PageIndex != this.PageCount)
            {
                this.PageIndex = Convert.ToInt32(this.PageIndex) + 1;
            }
            BindData();
        }

        public void LastPage()
        {
            this.PageIndex = this.PageCount;
            BindData();
        }

        public void DirectPage(int pageIndex)
        {
            if (pageIndex > this.PageCount || pageIndex <= 0)
            { this.BindData(); return; }

            this.PageIndex = pageIndex;
            this.BindData();
        }
        #endregion


        /// <summary>
        /// 绑定列表数据
        /// </summary>
        protected virtual void BindData()
        {
            throw new NotSupportedException("请在派生类中重写该方法");
        }

        /// <summary>
        /// 绑定相关命令事件
        /// </summary>
        protected void BindCommand()
        {
            throw new NotSupportedException("请在派生类中重写该方法");
        }

        #region 分页导航按钮事件
        /// <summary>
        /// 注册分页按钮事件
        /// </summary>
        internal virtual void RegPaginationHandler()
        {
            LinkButton lbtnFirst = this.GetControl<LinkButton>(this.FirstPageConID);
            if (lbtnFirst != null)
            {
                lbtnFirst.Text = StringRes.First;
                lbtnFirst.EnableViewState = false;
                lbtnFirst.Click += new EventHandler(OnFirstClick);
            }

            LinkButton lbtnPrev = this.GetControl<LinkButton>(this.PrevPageConID);
            if (lbtnPrev != null)
            {
                lbtnPrev.Text = StringRes.Previous;
                lbtnPrev.EnableViewState = false;
                lbtnPrev.Click += new EventHandler(OnPrevClick);
            }

            LinkButton lbtnNext = this.GetControl<LinkButton>(this.NextPageConID);
            if (lbtnNext != null)
            {
                lbtnNext.Text = StringRes.Next;
                lbtnNext.EnableViewState = false;
                lbtnNext.Click += new EventHandler(OnNextClick);
            }

            LinkButton lbtnLast = this.GetControl<LinkButton>(this.LastPageConID);
            if (lbtnLast != null)
            {
                lbtnLast.Text = StringRes.Last;
                lbtnLast.EnableViewState = false;
                lbtnLast.Click += new EventHandler(OnLastClick);
            }
        }

        protected void OnFirstClick(object sender, EventArgs e)
        {
            this.FirstPage();
        }
        protected void OnPrevClick(object sender, EventArgs e)
        {
            this.PrevPage();
        }
        protected void OnNextClick(object sender, EventArgs e)
        {
            this.NextPage();
        }
        protected void OnLastClick(object sender, EventArgs e)
        {
            this.LastPage();
        }

        /// <summary>
        /// 更新分页按钮显示状态
        /// </summary>
        public virtual void UpdatePaginationStatus()
        {
            LinkButton lbtnFirst = this.GetControl<LinkButton>(this.FirstPageConID);
            LinkButton lbtnPrev = this.GetControl<LinkButton>(this.PrevPageConID);
            LinkButton lbtnNext = this.GetControl<LinkButton>(this.NextPageConID);
            LinkButton lbtnLast = this.GetControl<LinkButton>(this.LastPageConID);

            int pagecount = this.PageCount;
            int pageindex = this.PageIndex;

            if (lbtnFirst != null && lbtnPrev != null)
            {
                if (this.PageIndex == 1)
                {
                    lbtnFirst.Enabled = false;
                    lbtnPrev.Enabled = false;
                }
                else
                {
                    lbtnFirst.Enabled = true;
                    lbtnPrev.Enabled = true;
                }
            }

            if (lbtnLast != null && lbtnNext != null)
            {
                if (this.PageIndex >= this.PageCount)
                {
                    lbtnLast.Enabled = false;
                    lbtnNext.Enabled = false;
                }
                else
                {
                    lbtnLast.Enabled = true;
                    lbtnNext.Enabled = true;
                }
            }
        }
        /// <summary>
        /// 注册数字分页按钮事件
        /// </summary>
        public void RegDigitPageHandler()
        {
            LinkButton lbtnTurnPage = this.GetControl<LinkButton>(this.TurnPageConID);
            if (lbtnTurnPage != null)
            { lbtnTurnPage.Click += new EventHandler(OnDigitPageClick); }
        }
        /// <summary>
        /// 数字分页按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnDigitPageClick(object sender, EventArgs e)
        {
            string argument = Request.Params["__EVENTARGUMENT"];
            int currentPage = HtmlHelper.StrToInt(argument, 0);
            if (currentPage == 0)
            {
                this.BindData();
            }
            else if (currentPage > 0)
            {
                this.PageIndex = currentPage;
                this.BindData();
            }
        }
        /// <summary>
        /// 创建数字分页页码事件
        /// </summary>
        public virtual void CreateDigitPageNavigation()
        {
            //用于数字分页按钮
            LinkButton lbtnTurnPage = this.GetControl<LinkButton>(this.TurnPageConID); //this.DataControl.FindControl(TurnPageConID) as LinkButton;
            string lbtnTurnPageClientID = lbtnTurnPage.UniqueID;

            //创建数字分页页码
            int totalPageNum = this.PageCount;   //总页数
            int startIndex = 1; //开始页码
            int endIndex = 1;   //结束页码
            StringBuilder sb = new StringBuilder();

            int midIndex = SUB_SIZE / 2;
            if (this.PageCount <= SUB_SIZE)
            {
                startIndex = 1;
            }
            else if ((this.PageCount - this.PageIndex) < midIndex)
            {
                startIndex = this.PageCount - SUB_SIZE + 1;
            }
            else
            {
                if (this.PageIndex <= midIndex)
                { startIndex = 1; }
                else
                { startIndex = this.PageIndex - midIndex; }
            }
            endIndex = startIndex + SUB_SIZE;
            sb.Append("<span class='Separate'></span>");
            for (int i = startIndex; i < endIndex; i++)
            {
                if (i != this.PageIndex)
                {
                    string script = string.Format("javascript:__doPostBack('{0}','{1}');", lbtnTurnPageClientID, i);
                    sb.AppendFormat("<a href={0} class='pb'>{1}</a>", script, i.ToString());
                }
                else
                { sb.AppendFormat("<span class='cpb'>{0}</span>", i.ToString()); }

                if (i >= totalPageNum) break;
            }
            sb.Append("<span class='Separate' /></span>");

            //设置数字导航
            Label lbDigitPage = this.GetControl<Label>(this.DigitPageConID); //this.DataControl.FindControl(this.DigitPageConID) as Label;
            if (lbDigitPage != null)
            {
                lbDigitPage.Text = sb.ToString();
            }

            Label lbPageDetail = this.GetControl<Label>(this.PageDetailConId); //this.DataControl.FindControl(this.PageDetailConId) as Label;
            if (lbPageDetail != null)
            {
                lbPageDetail.Text = string.Format(StringRes.PageDetail, this.PageCount, this.RowCount);
            }
        }
        #endregion

        #region 分页属性信息
        /// <summary>
        /// 当前查询条件
        /// </summary>
        public string QueryWhere
        {
            set
            {
                ViewState["QueryWhere"] = value;
            }
            get
            {
                if (ViewState["QueryWhere"] != null)
                {
                    return ViewState["QueryWhere"].ToString();
                }
                else
                {
                    return "1=1";
                }
            }
        }
        /// <summary>
        /// 当前分页页面索引
        /// </summary>
        public int PageIndex
        {
            set
            {
                ViewState["PageIndex"] = value;
            }
            get
            {
                int pageIndex = 1;
                if (ViewState["PageIndex"] != null)
                {
                    int.TryParse(ViewState["PageIndex"].ToString(), out pageIndex);
                }
                return pageIndex;
            }
        }
        /// <summary>
        /// 当前分页页面数量
        /// </summary>
        public int PageCount
        {
            set
            {
                ViewState["PageCount"] = value;
            }
            get
            {
                int pageCount = 1;
                if (ViewState["PageCount"] != null)
                {
                    int.TryParse(ViewState["PageCount"].ToString(), out pageCount);
                }
                return pageCount;
            }
        }
        /// <summary>
        /// 每页显示的记录数
        /// </summary>
        public virtual int PageSize
        {
            get
            {
                if (ViewState["PageSize"] == null)
                { return 10; }

                return (int)ViewState["PageSize"];
            }
            set { ViewState["PageSize"] = value; }
        }

        /// <summary>
        /// 总记录数
        /// </summary>
        public int RowCount
        {
            get
            {
                if (ViewState["RowCount"] == null)
                { return 0; }

                return (int)ViewState["RowCount"];
            }
            set { ViewState["RowCount"] = value; }
        }

        protected Control DataControl
        { get; set; }

        #endregion

        #region 控件名称属性信息

        /// <summary>
        /// 用于数字分页按钮名称
        /// </summary>
        protected string TurnPageConID
        {
            get { return "lbtnTurnPage"; }
        }

        #endregion

        #region 开放虚函数

        /// <summary>
        /// 页面处理虚方法
        /// </summary>
        public virtual void ShowListPage()
        {
            return;
        }
        /// <summary>
        /// 增加绑定事件完成后的处理事件
        /// </summary>
        protected virtual void Basic_DataBoundComplete()
        {

        }

        /// <summary>
        /// 返回查询列表数据(需要返回总记录数等数值)
        /// </summary>
        protected virtual ICollection GetBindDataObject(ref int rowCount)
        {
            throw new NotImplementedException("请设置数据源");
        }
                
        #endregion

        /// <summary>
        /// 获取页面控件
        /// </summary>
        /// <typeparam name="TControl"></typeparam>
        /// <param name="id"></param>
        /// <returns></returns>
        protected TControl GetControl<TControl>(string id) where TControl : Control
        {
            TControl tControl = default(TControl);

            Control con = this.DataControl.FindControl(id);
            if (con != null)
            {
                tControl = con as TControl;
            }
            return tControl;
        }
    }
}
